//
//  LaunchAdView.swift
//  DLReader
//
//  Created by mac1012 on 2017/5/31.
//  Copyright © 2017年 DianlE. All rights reserved.
//

import UIKit

class LaunchAdView: UIView {

    let screenW = UIScreen.main.bounds.width
    let screenH = UIScreen.main.bounds.height
    var myWindow:UIWindow?
    var adView = UIView()
    var countBtn = UIButton()
    var webURL: URL?
    var countTimer: Timer?{
        didSet{
            RunLoop.main.add(countTimer!, forMode: .commonModes)
        }
    }
    var count: NSInteger?
//    {
//        didSet {
//            RunLoop.main.add(countTimer!, forMode: .commonModes)
//        }
//    }
    var touchBlock: ((URL?) -> ())?
    
    static func show(showTime:Int,touchBlock: @escaping ((URL?) -> ())){
        let view = LaunchAdView()
        view.touchBlock = touchBlock
        let window = UIWindow(frame: UIScreen.main.bounds)
        window.rootViewController = UIViewController()
        window.rootViewController?.view.backgroundColor = UIColor.white
        window.windowLevel = UIWindowLevelStatusBar + 1
        window.isHidden = false
        window.alpha = 1
        
        window.addSubview(view)
        view.myWindow = window
        view.count = showTime
        NotificationCenter.default.addObserver(view, selector: #selector(nativeDidFinishLoading), name: NSNotification.Name(rawValue: "nativeDidFinishLoading"), object: nil)
        Timer.scheduledTimer(timeInterval: 3, target: view, selector:#selector(nativeIsFinishLoading), userInfo: nil, repeats: false)
    }
    
    func nativeIsFinishLoading(){
        guard (self.countTimer != nil) else {
            if(AdvertisingManager.share().native.isReady()){
                return
            }
            return dismissAction()
        }
        
       
    }
    
    func nativeDidFinishLoading(){
        print( AdvertisingManager.share().native.adTitle)
        
        let webUrl = AdvertisingManager.share().native.adLandingPageUrl
        let adView = AdvertisingManager.share().native.primaryView(ofWidth: ScreenUtils.screenWidth())
        self.countTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(countDown), userInfo: nil, repeats: true)
        self.addSubview(adView!)
        self.countBtn.setTitle("跳过\(String(describing: self.count))", for: .normal)
        self.countBtn.isHidden = false
        self.bringSubview(toFront: self.countBtn)
        self.webURL = webUrl
        
    }
    
    

    
    init() {
        super.init(frame: CGRect(x: 0, y: 0, width: screenW, height: screenH))
        self.backgroundColor = UIColor.white
        
        adView.frame = self.bounds
        adView.isUserInteractionEnabled = true
        adView.contentMode = .scaleAspectFill
        adView.clipsToBounds = true
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(tapAction))
        adView.addGestureRecognizer(tap)
        self.addSubview(adView)
        
        let btnW: CGFloat = 60
        let btnH: CGFloat = 30
        countBtn.frame = CGRect(x: screenW - btnW - 24, y: btnH, width: btnW, height: btnH)
        countBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        countBtn.setTitleColor(.white, for: .normal)
        countBtn.backgroundColor = UIColor.init(white: 0.2, alpha: 0.6)
        countBtn.layer.cornerRadius = 4
        countBtn.addTarget(self, action: #selector(dismissAction), for: .touchUpInside)
        countBtn.isHidden = true
        self.addSubview(countBtn)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func tapAction() {
        if let block = touchBlock {
            block(webURL)
            dismissAction()
        }
    }
    
    func countDown() {
        guard var count = self.count else {
            return
        }
        count -= 1
        self.count = count
        countBtn.setTitle("跳过\(count)", for: .normal)
        if count == 0 {
            dismissAction()
        }
    }
    func dismissAction() {
       
        
        UIView.animate(withDuration: 0.3, animations: {
            self.alpha = 0
        }, completion: { (_) in
            self.removeFromSuperview()
        })
        AdvertisingManager.share().recyclePrimaryView()
        guard (self.countTimer != nil) else {
            return
        }
        countTimer!.invalidate()
        
    }
}
